import React from 'react';
import {Icon, message, Upload} from 'antd';
import Constants from '../../utils/Constants';
import {checkIllegalChar} from '../../utils/commons'

const R = require('ramda');

export default class SingleDragger extends React.Component {
    constructor(props) {
        super(props);
        this.initFileList(props.url, props.dataSource.systemCode, true);
    }

    componentWillReceiveProps(nextProps) {
        if (!R.equals(this.props.dataSource)(nextProps.dataSource)) {
            this.initFileList(nextProps.url, nextProps.dataSource.systemCode);
        }
    }

    getFiles = () => {
        return this.state.fileList;
    }

    getUrl = () => {
        return this.state.dbUrl;
    }

    parseUrl = (url, systemCode) => {
        let {DOWNLOAD_PREFIX, DOWNLOAD_TEXT, FILENAME_TEXT} = Constants.FILE;
        let temp = url.substring(url.lastIndexOf('/') + 1, url.length)
        let fileName = encodeURI(encodeURI(url.substring(url.lastIndexOf('/') + 1, url.length)));
        return DOWNLOAD_PREFIX + this.props.module + DOWNLOAD_TEXT + systemCode + FILENAME_TEXT + fileName + "&" + Constants.ACJSESSIONID + "=" + sessionStorage.getItem(Constants.ACJSESSIONID);
    }

    initFileList = (url, systemCode, flag) => {
        let fileList = [];
        if (!R.isNil(url) && !R.isEmpty(url)) {
            let file = {};
            file.uid = new Date().getTime() * -1;
            file.name = url.substring(url.lastIndexOf('/') + 1, url.length);
            file.status = "done";
            file.url = this.parseUrl(url, systemCode);
            fileList.push(file);
        };
        if (flag) this.state = { fileList, dbUrl: url, defaultFileList: fileList, defaultDbUrl: url };
        else this.setState({ fileList, dbUrl: url, defaultFileList: fileList, defaultDbUrl: url });
    }

    resetUpload = () => {
        this.setState({ fileList: this.state.defaultFileList, url: this.state.defaultDbUrl, dbUrl: this.state.defaultDbUrl });
    }

    beforeUpload = (file) => {
        let { MAX_FILE_SIZE, MAX_LENGTH_FILENAME, ILLEGAL_UPLOAD_FILE_NAME } = Constants.FILE;
        const isLtMax = file.size / 1024 / 1024 < MAX_FILE_SIZE;
        let validateFileType = R.contains(file.name.substr(file.name.lastIndexOf('.') + 1).toLocaleLowerCase(), Constants.ACCEPTFILETYPES);
        let fileName = file.name.substr(0, file.name.lastIndexOf('.'));
        let fileNameLength = fileName.length <= MAX_LENGTH_FILENAME;
        let illegalChar = checkIllegalChar(fileName, ILLEGAL_UPLOAD_FILE_NAME);
        if (!fileNameLength) message.error("文件名长度不允许超过" + MAX_LENGTH_FILENAME + "位！");
        if (!isLtMax) message.error(`文件大小超过${MAX_FILE_SIZE}M限制`);
        if (!validateFileType) message.error("文件后缀非法,目前只允许" + (this.props.isImport ? xls或xlsx : R.join('|')(Constants.ACCEPTFILETYPES)));
        if (!illegalChar) message.error("文件名不允许存在包含" + ILLEGAL_UPLOAD_FILE_NAME + "在内的非法字符");
        if (isLtMax && validateFileType && fileNameLength && illegalChar) {
            this.setState({ fileList: [file], dbUrl: undefined });
        }
        return false;
    };

    onUploadChange = (info) => {
        let file = info.fileList.length > 1 ? info.fileList[1] : info.fileList[0];
        let dbUrl = "";
        if (file && file.response && file.response.resultCode === "ok") {
            dbUrl = R.isEmpty(dbUrl) ? file.response.content[0].url : dbUrl;
            file.url = this.parseUrl(dbUrl);
            file = R.pick(['uid', 'name', 'status', 'url'])(file);
            this.setState({ fileList: [file], dbUrl });
        } else if (file && file.response && !R.isNil(file.response.error)) {
            message.error(file.response.message);
            this.setState({ fileList: [], dbUrl: null });
        } else {
            file = R.pick(['uid', 'name', 'status'])(file);
            this.setState({ fileList: [file], dbUrl });
        }
    }

    onRemoveFile = (file) => {
        this.setState({ fileList: [], dbUrl: "" });
    }

    render() {
        let disabled = R.isNil(this.props.disabled) ? false : this.props.disabled;
        let headers = { [Constants.ACJSESSIONID]: sessionStorage.getItem(Constants.ACJSESSIONID) };
        return (
            <Upload.Dragger fileList={this.state.fileList} action={null} headers={headers} disabled={disabled} multiple={false}
                onRemove={this.onRemoveFile.bind(this)} beforeUpload={this.beforeUpload.bind(this)}>
                <p className="ant-upload-drag-icon">
                    <Icon type="inbox" />
                </p>
                {this.props.isImport ? 
                    <p className="ant-upload-text">请上传后缀名为xls|xlsx的文件</p>
                    :
                    <p className="ant-upload-text">多文件请压缩(原文件将被覆盖)</p>
                }
            </Upload.Dragger>
        );
    }
}

SingleDragger.propTypes = {
    module: React.PropTypes.string.isRequired
}